package mapper

import (
	"encoding/json"
	"fmt"
	"net/http"
	"work/config"

	"github.com/gin-gonic/gin"
	"github.com/hyperledger/fabric-gateway/pkg/client"
)

type Asset struct {
	ID    string `json:"id"`
	Owner string `json:"owner"`
	Name  string `json:"name"`
	Info  string `json:"info"`
}

// 调用合约的Get方法
func (Asset) Query(c *gin.Context) {
	key := c.Query("id")
	fmt.Print("调用Get方法，key值为：", key)
	evaluateResponse, err := config.Contract.EvaluateTransaction("Query", key)
	if err != nil {
		c.JSON(500, gin.H{"error": fmt.Sprintf("查询失败: %s", err.Error())})
		return
	}
	kv := new(Asset)
	_ = json.Unmarshal(evaluateResponse, kv)
	c.JSON(200, kv)
}

// 调用合约的Set方法
func (Asset) Create(c *gin.Context) {
	var asset Asset
	if err := c.ShouldBind(&asset); err != nil {
		fmt.Println("bind err:", err)
	}
	fmt.Println(asset)
	txn_proposal, err := config.Contract.NewProposal("Create", client.WithArguments(asset.ID,asset.Owner, asset.Name, asset.Info))
	if err != nil {
		c.JSON(500, gin.H{"error": fmt.Sprintf("创建交易提案失败: %s", err.Error())})
		return
	}
	txn_endorsed, err := txn_proposal.Endorse()
	if err != nil {
		c.JSON(500, gin.H{"error": fmt.Sprintf(" endorse 错误的提案: %s", err.Error())})
		return
	}
	txn_committed, err := txn_endorsed.Submit()
	if err != nil {
		c.JSON(500, gin.H{"error": fmt.Sprintf("提交交易失败: %s", err.Error())})
		return
	}
	fmt.Printf("提交交易成功，交易ID为：%s", txn_committed.TransactionID())
	c.String(http.StatusOK, txn_committed.TransactionID())
}

// 调用合约的Transfer方法
func (Asset) Transfer(c *gin.Context) {
	id := c.PostForm("id")
	owner := c.PostForm("owner")
	fmt.Printf("调用Set方法，key值为：%s，value值为：%s", id, owner)
	txn_proposal, err := config.Contract.NewProposal("Transfer", client.WithArguments(id, owner))
	if err != nil {
		c.JSON(500, gin.H{"error": fmt.Sprintf("创建交易提案失败: %s", err.Error())})
		return
	}
	txn_endorsed, err := txn_proposal.Endorse()
	if err != nil {
		c.JSON(500, gin.H{"error": fmt.Sprintf(" endorse 错误的提案: %s", err.Error())})
		return
	}
	txn_committed, err := txn_endorsed.Submit()
	if err != nil {
		c.JSON(500, gin.H{"error": fmt.Sprintf("提交交易失败: %s", err.Error())})
		return
	}
	fmt.Printf("提交交易成功，交易ID为：%s", txn_committed.TransactionID())
	c.String(http.StatusOK, txn_committed.TransactionID())
}
